package com.murphy.algorithm.demo;

/**
 * @author dongsufeng
 * @version 4.0
 * @date 2023/10/19 09:59
 */
public class FizzBuzz {
    volatile int number = 1;
    public static void main(String[] args){
        FizzBuzz fizzBuzz = new FizzBuzz();
        new Thread(() -> fizzBuzz.print("A")).start();
        new Thread(() -> fizzBuzz.print("B")).start();
        new Thread(() -> fizzBuzz.print("C")).start();
        new Thread(() -> fizzBuzz.print("D")).start();

    }

    Object object = new Object();
    public void print(String name){
        try {
            synchronized (object) {
                while (number <= 15) {
                    if (name.equals("A")) {
                        if (number % 3 == 0) {
                            System.out.println("fizz");
                            number++;
                            object.notifyAll();
                        } else {
                            object.wait();
                        }
                    } else if (name.equals("B")) {
                        if (number % 5 == 0) {
                            System.out.println("buzz");
                            number++;
                            object.notifyAll();
                        } else {
                            object.wait();
                        }
                    } else if (name.equals("C")) {
                        if (number % 3 == 0 && number % 5 == 0) {
                            System.out.println("fizzbuzz");
                            number++;
                            object.notifyAll();
                        }else {
                            object.wait();
                        }
                    }else {
                        if (number % 3 != 0 && number % 5 != 0) {
                            System.out.println(number);
                            number++;
                            object.notifyAll();
                        }else {
                            object.wait();
                        }
                    }
                }
            }
        }catch (Exception e){

        }
    }

}
